const express = require('express')
const router = express.Router()
const pool = require('../pool')

// sidebar
router.get("/", (req, res) => {
  var sql = "select * from user";
  pool.query(sql, [], (err, result) => {
    if (err) throw err
    //数据处理
    var cityList = []
    for (var i = 0; i < result.length; i++) {
      var address = result[i].address
      if (toCom(address)) {
        cityList.push({ address });
      }
      function toCom(address) {
        for (var i = 0; i < cityList.length; i++) {
          if (cityList[i].address === address) {
            return false
          }
        }
        return true
      }
    }
    for (var i = 0; i < cityList.length; i++) {
      var teacherList = []
      var managerList = []
      for (var k = 0; k < result.length; k++) {
        if (cityList[i].address === result[k].address) {
          if (result[k].position == 0) {
            teacherList.push(result[k]);
          } else {
            managerList.push(result[k]);
          }
        }
      }
      cityList[i].teacher = teacherList;
      cityList[i].manager = managerList;
    }

    res.send(cityList)
  })
})
// 查询员工全部数据
router.get('/userAll', (req, res) => {
  var sql = "select * from user"
  pool.query(sql, [], (err, result) => {
    if (err) throw err
    res.send({ code: 1, data: result })
  })
})
// 添加员工
router.post('/adduser', (req, res) => {
  var username = req.body.username
  var password = req.body.password
  var position = req.body.position
  var address = req.body.address
  res.writeHead(200, { "Content-Type": "application/json;charset=utf-8", "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Credentials": "true" });
  new Promise(open => {
    pool.query("select username from user where username=?", [username], (err, result) => {
      if (err) throw err
      if (result.length > 0) {
        res.write(JSON.stringify({ ok: 0, msg: "当前用户名已存在" }))
        res.end()
      } else {
        open()
      }
    })
  }).then(() => {
    return new Promise(open => {
      pool.query("INSERT INTO user VALUES(?,?,?,?,?,?)", ['', username, password, position, address, 0], (err, result) => {
        if (err) throw err
        if (result.affectedRows > 0) {
          open()
        } else {
          res.write(JSON.stringify({ ok: 0, msg: "添加失败！" }))
          res.end()
        }
      });
    });
  }).then(() => {
    res.write(JSON.stringify({ ok: 1, msg: "添加成功！" }))
    res.end()
  })
})
// 修改员工
router.post('/update', (req, res) => {
  var id = req.body.id
  var username = req.body.username
  var password = req.body.password
  var position = req.body.position
  var address = req.body.address
  res.writeHead(200, { "Content-Type": "application/json;charset=utf-8", "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Credentials": "true" })
  new Promise(open => {
    pool.query("select username from user where id<>? and username=?", [id, username], (err, result) => {
      if (err) throw err
      if (result.length > 0) {
        res.write(JSON.stringify({ ok: 0, msg: "当前用户名已存在" }))
        res.end()
      } else {
        open()
      }
    })
  }).then(() => {
    return new Promise(open => {
      pool.query("update user set username=?,password=?,position=?,address=? where id=?", [username, password, position, address, id], (err, result) => {
        if (err) throw err
        if (result.affectedRows > 0) {
          open()
        } else {
          res.write(JSON.stringify({ ok: 0, msg: "修改失败！" }))
          res.end()
        }
      })
    })
  }).then(() => {
    res.write(JSON.stringify({ ok: 1, msg: "修改成功！" }))
    res.end()
  })
})
// 删除员工
router.post('/delete', (req, res) => {
  var id = req.body.id
  res.writeHead(200, { "Content-Type": "application/json;charset=utf-8", "Access-Control-Allow-Origin": "*" })
  pool.query("DELETE FROM user where id=?", [id], (err, result) => {
    if (err) throw err;
    if (result.affectedRows > 0) {
      res.write(JSON.stringify({ ok: 1, msg: "删除成功！" }))
    } else {
      res.write(JSON.stringify({ ok: 0, msg: "删除失败！" }))
    }
    res.end()
  })
})

// 登录
router.post('/login', (req, res) => {
  var username = req.body.username
  var password = req.body.password
  var ok = 0
  Promise.all([
    new Promise(open => {
      var sql = "SELECT id,position,username FROM user WHERE username=? AND binary password=?";
      pool.query(sql, [username, password], (err, result) => {
        if (err) throw err;
        if (result.length > 0) {
          pool.query("update user set time=? WHERE id=?", [new Date().getTime(), result[0].id], (err, result) => {
            if (err) throw err;
          });
          ok++;
        }
        if (result.length > 0) {
          this.arr = result
        }

        open();
      });
    }),
    new Promise(open => {
      var sql = "SELECT id,position,name FROM admin WHERE name=? AND binary password=?";
      pool.query(sql, [username, password], (err, result) => {
        if (err) throw err;
        if (result.length > 0) {
          pool.query("update admin set time=? WHERE id=?", [new Date().getTime(), result[0].id], (err, result) => {
            if (err) throw err;
          });
          ok++;
        }
        if (result.length > 0) {
          this.arr = result
        }
        open();
      });
    })
  ]).then(() => {
    if (ok == 1) {
      res.write(JSON.stringify({ ok: 1, msg: "登录成功！", data: this.arr }));
    } else {
      res.write(JSON.stringify({ ok: 0, msg: "用户名或密码不正确,请重试！" }));
    }
    res.end();
  })
})
module.exports = router;

